Fork me on GitHub

93. Restore IP Addresses

93. Restore IP Addresses

题目

Given a string containing only digits, restore it by returning all possible valid IP address combinations.

For example:
Given "25525511135",

return ["255.255.11.135", "255.255.111.35"]. (Order does not matter)

解析

class Solution_93 {
public:
	bool isValid(string str)
	{
		long temp = atol(str.c_str()); //用int溢出;atol
		if (temp>255)
		{
			return false;
		}
		if (str[0]=='0'&&str.size()>1)
		{
			return false;
		}
		return true;
	}
	void dfs(vector<string> &res, string t, string s, int cnt)
	{
		if (cnt>3)
		{
			return;
		}
		if (cnt==3&&isValid(s)) //最后一组数
		{
			res.push_back(t+s);
			return;
		}
		for (int i = 1; i < 4 && i < s.size();i++)
		{
			string sub = s.substr(0, i);
			if (isValid(sub))
			{
				dfs(res, t + sub + '.', s.substr(i), cnt + 1);
			}
		}
		return;
	}

	vector<string> restoreIpAddresses(string s) {

		vector<string> res;
		string t;
		dfs(res,t,s,0);
		return res;
	}
};

题目来源

posted @ 2018-04-14 21:15  ranjiewen  阅读(149)  评论(0编辑  收藏  举报